<template>
  <div class="home-content">
    <div class="mapMark" id="mars3dContainer"></div>
    <div class="panel">
      <el-button
        type="info"
        @click="
          () => {
            polyton = [];
          }
        "
        >清空点位</el-button
      >
      <el-button type="info" @click="addPolyton(polyton)">存储点位</el-button>
      <el-button type="info" @click="addArea">添加街道</el-button>
      <el-button type="info" @click="addOtherArea">添加无关街道</el-button>
      <el-button type="info" @click="addwmsLayer">矢量地图</el-button>
      <el-button type="info" @click="removewmsLayer">移除矢量地图</el-button>
      <el-button type="info" @click="addDesic">添加遮罩</el-button>
      <el-button type="info" @click="drawArea">绘制面</el-button>
      <el-button type="info" @click="mapGetCameraView">获取视角</el-button>
      <el-button type="info" @click="backJd">返回街道</el-button>
    </div>
  </div>
</template>

<script setup>
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css";
import "mars3d-cesium";
import "mars3d/dist/mars3d.css";
import "mars3d";
import * as mars3d from "mars3d";
import { Cesium } from "mars3d";
import { onMounted } from "vue";
import { datajson, otherjson } from "./area.js";
import { MinMap } from "./map.js";
const { addPolyton } = MinMap();

onMounted(() => {
  initMap();
});

let map = null;
let polyton = ref([]);
// 初始化地图
const initMap = () => {
  // 创建三维地球场景
  map = new mars3d.Map("mars3dContainer", {
    scene: {
      center: {
        // alt: 34820.3,
        // heading: 3,
        // lat: 38.991913,
        // lng: 117.761415,
        // pitch: -70,
        lat: 38.865118, lng: 117.762385, alt: 18930.2, heading: 0.3, pitch: -54.7
      },
      showSun: false,
      showMoon: false,
      showSkyBox: false,
      showSkyAtmosphere: false, // 关闭球周边的白色轮廓 map.scene.skyAtmosphere = false
      fog: true,
      fxaa: true,
      globe: {
        showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
        depthTestAgainstTerrain: false,
        baseColor: "#546a53",
      },
      cameraController: {
        zoomFactor: 3.0,
        minimumZoomDistance: 1,
        maximumZoomDistance: 50000000,
        enableRotate: true,
        enableZoom: true,
      },
      mapProjection: mars3d.CRS.EPSG3857, // 2D下展示墨卡托投影
      mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL, // 2D下左右一直可以滚动重复世界地图
    },
    control: {
      baseLayerPicker: false, // basemaps底图切换按钮
      homeButton: false, // 视角复位按钮
      sceneModePicker: false, // 二三维切换按钮
      navigationHelpButton: false, // 帮助按钮
      fullscreenButton: false, // 全屏按钮
      contextmenu: { hasDefault: false }, // 右键菜单
    },
    basemaps: [
      // {
      //   name: "天地图影像",
      //   icon: "//data.mars3d.cn/img/control/basemap/tdt_img.png",
      //   type: "tdt",
      //   layer: "img_d",
      //   show: true,
      // },
      // {
      //   name: "高德电子",
      //   icon: "//data.mars3d.cn/img/thumbnail/basemap/gaode_vec.png",
      //   type: "gaode",
      //   layer: "vec",
      //   show: true,
      // },
      {
        name: "中科大-东区",
        type: "image",
        url: "//data.mars3d.cn/img/map/zkd-dq.png",
        rectangle: { xmin: 117.259691, xmax: 117.267778, ymin: 31.834432, ymax: 31.84387 },
        zIndex: 20,
        show: true
      }
    ],
  });

  map.on(mars3d.EventType.load, function (event) {
    console.log(`地图所有图层加载完成`);
    //添加 WMS图层
    //  addwmsLayer();
  });

  let timer = null;
  map.on(mars3d.EventType.click, (event) => {
    map.setCursor(false);
    const cartesian = event.cartesian;
    const point = mars3d.LngLatPoint.fromCartesian(cartesian);
    point.format(); // 经度、纬度、高度
    console.log(point);
    // if (timer) {
    //   clearTimeout(timer);
    //   timer = null;
    // }
    // timer = setTimeout(() => {
    //   console.log("单击地图");
    //   map.setCursor(false);
    //   const cartesian = event.cartesian;
    //   const point = mars3d.LngLatPoint.fromCartesian(cartesian);
    //   point.format(); // 经度、纬度、高度
    //   console.log(point);
    //   polyton.value.push([point._lng, point._lat]);
    // }, 300);
  });
  map.on(mars3d.EventType.dblClick, (event) => {
    // if (timer) {
    //   clearTimeout(timer);
    //   timer = null;
    // }
    // console.log("双击地图");
  });
};

let tileLayer = null;
// 添加 WMS图层
const addwmsLayer = () => {
  tileLayer = new mars3d.layer.WmsLayer({
    url: "/geoserver/wms",
    layers: "mytianjin",
    parameters: {
      transparent: true,
      format: "image/png",
      srs: "EPSG:4326", // 坐标系
    },
    popup: false, // "all"
    flyTo: false,
  });
  map.addLayer(tileLayer);
};

// 移除wms图层
const removewmsLayer = () => {
  map.removeLayer(tileLayer, true);
  tileLayer = null;
};

// 添加街道区域
let graphicLayerXg = null
const addArea = async () => {
  graphicLayerXg = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayerXg);
  let list = datajson;
  for (let i = 0; i < list.length; i++) {
    let polython = new mars3d.graphic.PolygonEntity({
      // let polython = new mars3d.graphic.Mask({
      positions: list[i].python,
      style: {
        zIndex: 1, // 设置zIndex
        color: "#3388ff",
        opacity: 0.8,
        outline: true,
        outlineWidth: 1,
        outlineColor: "#ffffff",
        // materialType: mars3d.MaterialType.PolyGradient, // 重要参数，指定材质
        // materialOptions: {
        //   color: "#144f7e",
        //   opacity: 0,
        //   alphaPower: 1,
        //   isInner: true,
        // },
      },
      attr: { ...list[i] },
      zIndex: 10,
    });
    graphicLayerXg.addGraphic(polython);
    polython.on(mars3d.EventType.click, (event) => {
      addSelectEntry(event.graphic.attr);
    });
    graphicLayerXg.addGraphic(
      new mars3d.graphic.DivGraphic({
        position: [...list[i].center],
        style: {
          html: `<div class="text-area">
                    ${list[i].name}
              </div>`,
          offsetY: 0,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            400000
          ), // 按视距距离显示
        },
        attr: { remark: "示例2" },
      })
    );
  }
};

// 添加选中效果
let catchLayer = null,
  graphicCartch = null;
const addSelectEntry = (gemo) => {
  // if (catchLayer) {
  //   catchLayer.removeGraphic(graphicCartch);
  // }
  // // 创建矢量数据图层
  // catchLayer = new mars3d.layer.GraphicLayer();
  // map.addLayer(catchLayer);
  // graphicCartch = new mars3d.graphic.PolygonEntity({
  //   positions: gemo.python,
  //   style: {
  //     height: 250,
  //     diffHeight: 200,
  //     outline: true,
  //     outlineWidth: 3,
  //     outlineColor: "#8ae3f3",
  //     outlineStyle: {
  //       height: 450,
  //       diffHeight: 450,
  //     },
  //     materialType: mars3d.MaterialType.PolyGradient,
  //     materialOptions: {
  //       color: "#05acd5",
  //       opacity: 1,
  //       alphaPower: 1,
  //       scale: 0.5,
  //     },
  //     hasShadows: true,
  //     shadows: Cesium.ShadowMode.CAST,
  //     zIndex: 100,
  //   },
  //   attr: { ...gemo },
  // });
  // catchLayer.addGraphic(graphicCartch);
  map.setCameraView({ lat: gemo.center[1], lng: gemo.center[0], alt: 10000, heading: 3, pitch: -90 })
  graphicLayerXg.show=false
};

// 返回街道层级

const backJd = () => {
  map.flyHome()
  graphicLayerXg.show=true
}

// 创建遮罩层

const addDesic = () => {
  const geoJsonLayer = new mars3d.layer.GeoJsonLayer({
    url: "./120116.json",
    mask: true, // 标识为遮罩层【重点参数】
    symbol: {
      styleOptions: {
        fill: true,
        color: "rgb(2,26,79)",
        opacity: 0.7,
        outline: false,
        outlineColor: "#39E09B",
        outlineWidth: 8,
        outlineOpacity: 0.8,
        arcType: Cesium.ArcType.GEODESIC,
        // global: false, // 是否全球遮罩，false时为中国区域
        clampToGround: true
      }
    }
    // flyTo: true
  })
  map.addLayer(geoJsonLayer)
};

// 添加其他街道
const addOtherArea = async () => {
  let graphicLayerName = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayerName);
  let namelist = otherjson;
  for (let i = 0; i < namelist.length; i++) {
    // graphicLayerName.addGraphic(
    //   new mars3d.graphic.PolygonEntity({
    //     // let polython = new mars3d.graphic.Mask({
    //     positions: namelist[i].python,
    //     style: {
    //       zIndex: 1, // 设置zIndex
    //       color: "#fff",
    //       opacity: 0.3,
    //       outline: false,
    //       outlineWidth: 1,
    //       outlineColor: "#ffffff",
    //     },
    //     attr: { ...namelist[i] },
    //     zIndex: 10,
    //   })
    // );
    graphicLayerName.addGraphic(
      new mars3d.graphic.DivGraphic({
        position: namelist[i].center,
        style: {
          html: `<div class="text-area">
                      ${namelist[i].name}
                </div>`,
          offsetY: 0,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            400000
          ), // 按视距距离显示
        },
        attr: { remark: "示例2" },
      })
    );
  }
};

// 绘制面

const drawArea = () => {
  // 创建矢量数据图层
  let graphicLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayer);
  graphicLayer.startDraw({
    type: "polygonP",
    style: {
      color: "#29cf34",
      opacity: 0.5,
      outline: true,
      outlineWidth: 1,
      outlineColor: "#29cf34",
      label: {
        text: "",
        font_size: 18,
        color: "#ffffff",
        distanceDisplayCondition: true,
        distanceDisplayCondition_far: 500000,
        distanceDisplayCondition_near: 0,
      },
    },
    success: (graphic) => {
      console.log(graphic.getCoordinates());
      localStorage.setItem(
        "pythonData",
        JSON.stringify(graphic.getCoordinates())
      );
    },
  });
};

let mapGetCameraView = () => {
  const camera = map.getCameraView();
  // globalAlert(JSON.stringify(camera), "当前视角参数")
  console.log(camera);
};
</script>

<style lang="scss">
.home-content {
  width: 100%;
  height: 100%;
  .mapMark {
    width: 100%;
    height: 100%;
  }
  .panel {
    position: fixed;
    left: 50px;
    top: 50px;
    z-index: 999;
  }
  .text-area {
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 4px;
    padding:12px;
    // background: rgba(0,0,0,0.5);
    border-radius:50%;
    text-align: center;
    opacity: 0.5;
  }
}
</style>